import L from 'leaflet';
import { DrawInteraction } from './DrawInteraction';
import { SelectInteraction } from './SelectInteraction';
import { flattenLatLngs } from './drawingUtils';

// 启动绘制模式（可持续绘制，直到手动停止）
export function startDrawMode(
  map: L.Map,
  drawInteractionRef: { current?: DrawInteraction },
  selectInteractionRef: { current?: SelectInteraction },
  mode: 'marker' | 'polyline' | 'polygon',
  addMarker?: (lat: number, lng: number, color: string, size: number, notify: boolean) => void,
  drawLine?: (points: L.LatLng[], color: string, weight: number, notify: boolean) => void,
  drawPolygon?: (points: L.LatLng[], color: string, fillColor: string, weight: number, notify: boolean) => void
) {
  if (!map) return;
  if (!drawInteractionRef.current) drawInteractionRef.current = new DrawInteraction(map);
  // 启动绘制前，先关闭选择模式，防止事件冲突
  selectInteractionRef.current?.disableSelect();
  // 标记已进入绘制模式
  (drawInteractionRef.current as any)._drawing = true;
  // 持续监听，每次绘制完成后自动重新进入该模式
  const drawOnce = () => {
    if (!(drawInteractionRef.current as any)._drawing) return; // 如果已停止则不再进入
    drawInteractionRef.current!.startDrawMode(mode, (points: L.LatLng[]) => {
      if (!(drawInteractionRef.current as any)._drawing) return;
      if (mode === 'marker') {
        const [pt] = points;
        (addMarker)?.(pt.lat, pt.lng, '#ff1744', 8, true);
      } else if (mode === 'polyline') {
        (drawLine)?.(points, '#ff9800', 3, true);
      } else if (mode === 'polygon') {
        (drawPolygon)?.(points, '#ff9800', '#ffe082', 3, true);
      }
      drawOnce();
    });
  };
  drawOnce();
}

// 停止绘制模式（关闭所有临时事件和图形）
export function stopDrawMode(
  drawInteractionRef: { current?: DrawInteraction },
  selectInteractionRef: { current?: SelectInteraction },
  enableSelectMode: (onSelect?: (layer: L.Layer | L.Layer[]) => void, mode?: 'single' | 'rectangle' | 'polygon') => void,
  lastSelectMode?: 'single' | 'rectangle' | 'polygon'
) {
  // 标记退出绘制模式
  if (drawInteractionRef.current) (drawInteractionRef.current as any)._drawing = false;
  drawInteractionRef.current?.clearDrawEvents();
  if (drawInteractionRef.current && drawInteractionRef.current.setMapCursor) {
    drawInteractionRef.current.setMapCursor('');
  }
  // 停止绘制时，恢复选择模式，使用上次的 selectMode
  if (typeof lastSelectMode === 'string') {
    enableSelectMode(undefined, lastSelectMode);
  } else {
    enableSelectMode();
  }
}

// 启用图层选择模式
export function enableSelectMode(
  map: L.Map,
  selectInteractionRef: { current?: SelectInteraction },
  markers: L.Layer[],
  lines: L.Layer[],
  polygons: L.Layer[],
  onSelect?: (layer: L.Layer | L.Layer[]) => void,
  mode: 'single' | 'rectangle' | 'polygon' = 'single'
) {
  if (!selectInteractionRef.current) {
    selectInteractionRef.current = new SelectInteraction(map);
  }
  // 每次启用选择前，先清除所有高亮
  [...markers, ...lines, ...polygons].forEach(layer => {
    if ((layer as any)._originalStyle) {
      (layer as any).setStyle?.((layer as any)._originalStyle);
    }
    // 兼容 L.GeoJSON 类型（FeatureGroup 或 LayerGroup）
    if ((layer as any).eachLayer) {
      (layer as any).eachLayer((subLayer: any) => {
        if (subLayer && subLayer.setStyle && subLayer._originalStyle) {
          subLayer.setStyle(subLayer._originalStyle);
        }
      });
    }
  });
  selectInteractionRef.current.setSelectMode(mode);
  // 绑定所有类型图层（点、线、面）
  selectInteractionRef.current.enableSelect([...markers, ...lines, ...polygons], onSelect);
}

// 关闭图层选择模式
export function disableSelectMode(selectInteractionRef: { current?: SelectInteraction }) {
  selectInteractionRef.current?.disableSelect();
}

// 获取当前选中图层
export function getSelectedLayer(selectInteractionRef: { current?: SelectInteraction }) {
  return selectInteractionRef.current?.getSelectedLayer();
}

// 缩放至所有图形范围
export function fitBounds(map: L.Map, markers: L.Layer[], lines: L.Layer[], polygons: L.Layer[]) {
  if (!map) return;
  const allLatLngs: L.LatLng[] = [];
  markers.forEach(m => allLatLngs.push((m as any).getLatLng?.()));
  lines.forEach(l => {
    if (typeof (l as any).getLatLngs === 'function') {
      const latlngs = (l as any).getLatLngs();
      if (Array.isArray(latlngs)) {
        allLatLngs.push(...(latlngs as L.LatLng[]));
      }
    }
  });
  polygons.forEach(p => {
    // 兼容 L.GeoJSON 类型
    if (typeof (p as any).getLatLngs === 'function') {
      let latlngs = (p as any).getLatLngs();
      // 彻底拍平成一维 L.LatLng[]
      const flat = flattenLatLngs(latlngs);
      allLatLngs.push(...flat);
    } else if ((p as any).getBounds) {
      // L.GeoJSON 没有 getLatLngs，但有 getBounds
      const bounds = (p as any).getBounds?.();
      if (bounds && bounds.isValid && bounds.isValid()) {
        allLatLngs.push(bounds.getSouthWest());
        allLatLngs.push(bounds.getNorthEast());
      }
    }
  });
  if (allLatLngs.length > 0) {
    map.fitBounds(L.latLngBounds(allLatLngs));
  }
}
